import React, { Component } from 'react';
//导入日期类库
import moment from 'moment';
class Time extends Component {
    state = {
        timestr: moment().format("YYYY-MM-DD HH:mm:ss"),
    }
    //在组件实例化对象身上定义timerid
    timerid = null
    render() {
        let { timestr } = this.state;
        return (
            <div style={{ width: 200, height: 30, border: '1px dashed #ccc', lineHeight: '30px', textAlign: 'center' }}>
                {timestr}
            </div>
        );
    }

    //这个方法默认只执行一次，除非这个组件卸载了，才会重新挂载
    componentDidMount() {
        console.log('组件挂载完成了............');
        // console.log(this); //组件实例化对象
        //定时器
        this.timerid = setInterval(() => {
            // console.log('定时器....')
            //修改state状态数据
            this.setState({
                timestr: moment().format("YYYY-MM-DD HH:mm:ss")
            })
        }, 1000);
    }

    componentWillUnmount() {
        // console.log('实例化对象', this)
        clearInterval(this.timerid)
    }

    componentDidUpdate() {
        // console.log('实例化对象', this);
    }
}

export default Time;